/**
 * Created by Rui on 2016/5/10.
 */
(function(){
    
    function $(id){
        return document.getElementById(id);
    }
    
    var num_input = $("num-input");
    var left_in = $("left-in");
    var left_out = $("left-out");
    var right_in = $("right-in");
    var right_out = $("right-out");
    var display = $("display");


    function checkNum(){
        num = num_input.value.trim();
        num_input.value = "";
        if(isNaN(parseInt(num)) || num === undefined || num=='' || num===null){
            return false;
        }
        return num;
    }

    function bindEvent(ele, event_name, func){
        if(window.addEventListener){
            event_name = event_name.replace(/^on/,"");
            ele.addEventListener(event_name, func, false);
        }else if(window.attachEvent){
            ele.attachEvent(event_name, func);
        }else {
            ele[event_name] = func;
        }
    }

    function numDiv(num){
        var div = document.createElement("div");
        div.className = "num";
        var text = document.createTextNode(num);
        div.appendChild(text);
        return div;
    }

    bindEvent(left_in, "onclick", function(){
        var num = checkNum();
        if(num !== false){
            var newDiv = numDiv(num);
            var firstChild = display.firstChild;
            if(firstChild == null){
                display.appendChild(newDiv);
            }else {
                display.insertBefore(newDiv, firstChild);
            }
        }
    })

    bindEvent(left_out, "onclick", function(){
        var firstChild = display.firstChild;
        if (firstChild !== null && firstChild !== undefined){
            display.removeChild(firstChild);
        }
    })

    bindEvent(right_in, "onclick", function () {
        var num = checkNum();
        if(num !== false){
            var newDiv = numDiv(num);
            display.appendChild(newDiv);
        }
    })

    bindEvent(right_out, "onclick", function(){
        var lastChild = display.lastChild;
        if (lastChild !== null && lastChild !== undefined) {
            display.removeChild(lastChild);
        }
    })

    //事件代理，display， 代理 子元素数字节点
    bindEvent(display, "onclick", function (event) {
        var clickDiv = event.target;
        if(clickDiv.className === "num"){
            display.removeChild(clickDiv);
        }

    })
})();
























